package com.fun.feifun.modules.business.controller;
import cn.dev33.satoken.annotation.SaCheckLogin;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fun.feifun.base.utils.ControlUtils;
import com.fun.feifun.modules.business.model.BusinessAmountRecord;
import com.fun.feifun.modules.business.model.BusinessGoods;
import com.fun.feifun.modules.business.model.dto.BusinessAmountRecordDto;
import com.fun.feifun.modules.business.model.dto.BusinessGoodsRouteDto;
import com.fun.feifun.modules.business.model.dto.BusinessUserDto;
import com.fun.feifun.modules.business.model.dto.BusinessUserGoodsDto;
import com.fun.feifun.modules.business.model.param.*;
import com.fun.feifun.modules.business.service.IBusinessAmountRecordService;
import com.fun.feifun.modules.business.service.IBusinessUserGoodsService;
import java.util.Base64;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fun.feifun.modules.business.service.IBusinessUserService;
import com.fun.feifun.modules.business.model.BusinessUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.fun.feifun.base.result.Result;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;

import java.math.BigDecimal;
import java.security.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务代理用户 前端控制器
 * </p>
 *
 * @author wkf
 * @since 2024-05-29
 */
@RestController
@Api(value = "/business/business-user", tags = "业务代理用户")
@Slf4j
@SaCheckLogin()
@RequestMapping("/business/business-user")
public class BusinessUserController {


    @Autowired
    private IBusinessUserService service;

    @Autowired
    private IBusinessAmountRecordService amountRecordService;

    @Autowired
    private IBusinessUserGoodsService userGoodsService;
    /**
     * 获取分页
     */
    @PostMapping("/page")
    @ApiOperation(value = "获取分页信息")
    public Result<Page<BusinessUserDto>> page(@RequestBody BusinessUserPage param){
        Page page = new Page(param.getPage(),param.getSize());
        QueryWrapper<BusinessUser>  wrapper=new QueryWrapper<>();
        if(StringUtils.isNotEmpty(param.getCode())){
            wrapper.lambda().like(BusinessUser::getCode,param.getCode());
        }
        if(StringUtils.isNotEmpty(param.getUserName())){
            wrapper.lambda().like(BusinessUser::getCode,param.getUserName());
        }
        wrapper.lambda().eq(BusinessUser::getDelFlag,false);
        service.page(page,wrapper);
        List<BusinessUser> list = page.getRecords();
        List<BusinessUserDto> records =list.stream().map(it->it.toDto()).collect(Collectors.toList());
        List<Long> userIds = records.stream().map(it -> it.getId()).collect(Collectors.toList());
        if(ControlUtils.isNotEmpty(userIds)){
            Map<Long, Long> userGoodsCount = userGoodsService.getUserGoodsCount(userIds);
            records.forEach(it->{
                if(userGoodsCount.containsKey(it.getId())){
                    it.setGoodsCount(userGoodsCount.get(it.getId()));
                }
            });
        }
        page.setRecords(records);
        return Result.success(page);
    }



    /**
     * 添加数据
     */
    @PostMapping(value = "/save")
    @ApiOperation(value = "添加或者保存")
    public Result save(@RequestBody BusinessUser item){
        QueryWrapper<BusinessUser> wrapper=new QueryWrapper();
        wrapper.lambda().eq(BusinessUser::getCode,item.getCode());
        BusinessUser one = service.getOne(wrapper);
        if(item.getId()==null&& ObjectUtils.isNotEmpty(one)){
            return Result.err("添加用户code重复，添加失败！");
        }
        if(item.getId()!=null&&ObjectUtils.isNotEmpty(one)&&!one.getId().equals(item.getId())){
            return Result.err("修改用户code重复，修改失败！");
        }
        if(service.saveOrUpdate(item)){
         return Result.success("数据添加成功！");
        }
        return Result.err("数据添加成功！");
    }



    /**
     * 删除数据
     */
    @DeleteMapping("/del")
    @ApiOperation(value = "删除")
    public Result deleteItems(@RequestBody List<Long> ids){
        UpdateWrapper<BusinessUser> wrapper=new UpdateWrapper();
        wrapper.lambda().set(BusinessUser::getDelFlag,true).in(BusinessUser::getId,ids);
        if(service.update(wrapper)){
            return Result.success("数据删除成功！");
        }
        return Result.err("数据删除失败");
    }


    /**
     * 根据ID查找数据
     */
    @PostMapping("/findById")
    @ApiOperation(value = "查找")
    public Result findById(@RequestParam("id") Long id){
        BusinessUser item = service.getById(id);
        if(item==null){
            return Result.err("尚未查询到此ID");
        }
        return Result.success(item);
    }


    /**
     * 手动充值
     */
    @PostMapping("/recharge")
    @ApiOperation(value = "手动充值")
    @Transactional
    public Result recharge(@RequestParam("userId") Long userId,@RequestParam("amount") Double amount){
         BusinessUser item = service.getById(userId);
         if(ObjectUtils.isEmpty(item)){
             return Result.err("操作用户不存在");
         }
        BigDecimal oldAmount = item.getAmount();
        BigDecimal nowAmount = new BigDecimal(amount);
        BigDecimal newAmount = item.getAmount().add(nowAmount);

        UpdateWrapper<BusinessUser> wrapper=new UpdateWrapper<>();
        wrapper.lambda().set(BusinessUser::getAmount,newAmount).eq(BusinessUser::getId,userId);
        boolean update = service.update(wrapper);
        BusinessAmountRecord record=new BusinessAmountRecord();
        record.setUserId(item.getId());
        record.setAmount(nowAmount);
        record.setBeforeAmount(oldAmount);
        record.setAfterAmount(newAmount);
        record.setRemake("加款记录");
        boolean save = amountRecordService.save(record);
        if(update&&save){
            return Result.success();
        }else {
            throw new RuntimeException("添加金额失败");
        }
    }

    /**
     * 获取分页
     */
    @PostMapping("/getAmountRecordPage")
    @ApiOperation(value = "获取充值记录分页")
    public Result<Page<BusinessAmountRecordDto>> amountRecordPage(@RequestBody BusinessAmountRecordPage param){
        Page<BusinessAmountRecordDto> page = amountRecordService.getDtoPage(param);
        return Result.success(page);
    }

    @PostMapping("/getUserGoodsList")
    @ApiOperation(value = "获取用户商品列表")
    public Result<List<BusinessUserGoodsDto>> getUserGoodsPage(@RequestBody BusinessUserParam param){
        List<BusinessUserGoodsDto> list = userGoodsService.getUserDtoPage(param);
        return Result.success(list);
    }

    @PostMapping("/setUserGoods")
    @ApiOperation(value = "设置用户商品")
    public Result setUserGoods(@RequestBody BusinessUserGoodsParam param){
        List<BusinessUserGoodsParam.GoodsFees> goodsList = param.getGoodsList();
        Set<Long> set = goodsList.stream().map(it -> it.getGoodsId()).collect(Collectors.toSet());
        if(set.size()!=param.getGoodsList().size()){
            return Result.success("用户设置中的商品重复,请检查。");
        }
        if(userGoodsService.saveUserGoods(param)){
            return Result.success("设置成功");
        }else{
            return Result.success("设置失败");
        }
    }

    @GetMapping("/generateSecretKey")
    @ApiOperation(value = "生成密匙")
    public Result<BusinessUser> generateSecretKey(@RequestParam("userId") Long userId){

        BusinessUser user=service.getById(userId);
        // 创建一个SecureRandom实例
        SecureRandom random = new SecureRandom();
        // 密钥长度为16字节（128位）
        byte[] keyBytes = new byte[16];
        // 生成随机密钥
        random.nextBytes(keyBytes);
        // 将字节转换为Base64编码字符串
        String key = Base64.getEncoder().encodeToString(keyBytes);
        user.setSecretKey(key);
        boolean update = service.updateById(user);
        if(update){
            return Result.success("生成成功");
        }else{
            return Result.success("生成失败");
        }
    }

//    @PostMapping("/setUserGoodsFees")
//    @ApiOperation(value = "设置用户商品手续费")
//    public Result<Page<BusinessAmountRecordDto>> setUserGoodsFees(@RequestBody BusinessAmountRecordPage param){
//        Page<BusinessAmountRecordDto> page = amountRecordService.getDtoPage(param);
//        return Result.success(page);
//    }

    @PostMapping("/operationUser")
    @ApiOperation(value = "操作用户停用/启用")
    public Result operationGoods(@RequestBody BusinessUserOperation param){
        UpdateWrapper<BusinessUser> wrapper=new UpdateWrapper<>();
        wrapper.lambda().in(BusinessUser::getId,param.getIds()).set(BusinessUser::getIsEnable,param.getIsEnable());
        boolean update = service.update(wrapper);
        if(update){
            return Result.success("操作成功");
        }
        return Result.err("操作失败");
    }



    @PostMapping("/editCreditAmount")
    @ApiOperation(value = "修改额度")
    @Transactional
    public Result editCreditAmount(@RequestParam("userId") Long userId,@RequestParam("amount") Double amount){
        BusinessUser item = service.getById(userId);
        if(ObjectUtils.isEmpty(item)){
            return Result.err("操作用户不存在");
        }
        item.setCreditAmount(BigDecimal.valueOf(amount));
        boolean update = service.updateById(item);
        if(update){
            return Result.success();
        }else {
            throw new RuntimeException("修改失败");
        }
    }
}

